package com.nulldev.util.analytics;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.util.LinkedList;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import com.nulldev.util.io.MD5Utils;
import com.nulldev.util.java.JVMUtil;
import com.nulldev.util.java.swing.SwingUtil;
import com.nulldev.util.java.swing.extSwing.lookandfeel.themes.ThemeApplier;
import com.nulldev.util.java.swing.utils.MultiLineToolTipUI;
import com.nulldev.util.net.IPUtil;
import com.nulldev.util.os.CPUUtil;
import com.nulldev.util.os.GPUUtil;
import com.nulldev.util.os.OSUtil;
import com.nulldev.util.other.ArrayUtils;
import com.nulldev.util.string.StringsUtil;

import javax.swing.JScrollPane;
import javax.swing.JList;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.LayoutStyle.ComponentPlacement;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextPane;
import javax.swing.JButton;

public class nAnalyticsSettingsUI extends JFrame {

	private static final nAnalytics demoData = new nAnalytics("nAnalytics.dataSampler");
	private static nAnalyticsSettingsUI instance;
	private JPanel contentPane;
	private JList list;
	private JPanel panel_1;
	private JTextPane textPane;

	/**
	 * Launch the application.
	 */
	public static void main() {
		if (!MultiLineToolTipUI.installed()) {
			MultiLineToolTipUI.installUI();
		}
		if (instance == null) {
			EventQueue.invokeLater(new Runnable() {
				public void run() {
					try {
						nAnalyticsSettingsUI frame = new nAnalyticsSettingsUI();
						ThemeApplier.applyTheme(frame);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
	}
	
	public static nAnalyticsSettingsUI get() {
		return instance;
	}
	
	public static void toggle() {
		if (instance == null) {
			main();
			return;
		}
		if (instance != null) {
			instance.updateList(nAnalyticsSettings.cloneList());
			instance.setVisible(!instance.isVisible());
			SwingUtil.centerFrame(instance);
		}
	}

	/**
	 * Create the frame.
	 */
	public nAnalyticsSettingsUI() {
		this.instance = this;
		
		setTitle("nAnalytics: Settings");
		//setResizable(false);
		setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		setBounds(100, 100, 544, 501);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new BorderLayout(0, 0));
		
		panel_1 = new JPanel();
		contentPane.add(panel_1, BorderLayout.CENTER);
		
		final JCheckBox chckbxAllowDetailedOs = new JCheckBox("Allow Detailed OS Data");
		chckbxAllowDetailedOs.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				nAnalyticsSettings.allowOSFull = chckbxAllowDetailedOs.isSelected();
				try {
					nAnalyticsSettings.analyticsSettings.writeOption("analytics.noOS", !chckbxAllowDetailedOs.isSelected());
				}catch (Exception ex) {}
				textPane.setText(ArrayUtils.StringArrayUtils.addFrom(demoData.fetch_data_dump(), 0));
			}
		});
		chckbxAllowDetailedOs.setSelected(nAnalyticsSettings.allowOSFull);
		chckbxAllowDetailedOs.setToolTipText("Your Data: " + OSUtil.getOperatingSystemString() + JVMUtil.lineSep() + "Disabling this will only grant os type." + JVMUtil.lineSep() + "Example: Linux.");
		
		JLabel lblHoverOverA = new JLabel("Hover over a checkbox to see an example.");
		
		JLabel lblTheFloowingBoxes = new JLabel("The selected boxes will be queried.");
		
		final JCheckBox chckbxAllowNetworkData = new JCheckBox("Allow Network Data");
		chckbxAllowNetworkData.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				nAnalyticsSettings.allowNetwork = chckbxAllowNetworkData.isSelected();
				try {
					nAnalyticsSettings.analyticsSettings.writeOption("analytics.noNetwork", !chckbxAllowNetworkData.isSelected());
				}catch (Exception ex) {}
				textPane.setText(ArrayUtils.StringArrayUtils.addFrom(demoData.fetch_data_dump(), 0));
			}
		});
		chckbxAllowNetworkData.setSelected(nAnalyticsSettings.allowNetwork);
		chckbxAllowNetworkData.setToolTipText("Your Data: " + IPUtil.getPublicIP());
		
		JScrollPane scrollPane = new JScrollPane();
		
		JLabel lblRegisteredAnalytics = new JLabel("Registered Analytics:");
		
		final JCheckBox chckbxAllowUid = new JCheckBox("Allow UID");
		chckbxAllowUid.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				nAnalyticsSettings.allowUID = chckbxAllowUid.isSelected();
				try {
					nAnalyticsSettings.analyticsSettings.writeOption("analytics.noUID", !chckbxAllowUid.isSelected());
				}catch (Exception ex) {}
				textPane.setText(ArrayUtils.StringArrayUtils.addFrom(demoData.fetch_data_dump(), 0));
			}
		});
		chckbxAllowUid.setSelected(nAnalyticsSettings.allowUID);
		final String[] args = new String[] {OSUtil.getOperatingSystemType().toString(), IPUtil.getInternetLocalIP_Safe(), CPUUtil.parse().toString(), GPUUtil.parse().toString()};
		final String uuid = MD5Utils.getMD5Hex(ArrayUtils.StringArrayUtils.addFrom(args, 0));
		
		chckbxAllowUid.setToolTipText("UID/Your PC's unique identifer." + JVMUtil.lineSep() + "Your Data: " + uuid);
		
		JCheckBox chckbxAllowCpuData = new JCheckBox("Allow CPU Data");
		chckbxAllowCpuData.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				nAnalyticsSettings.allowCPU = chckbxAllowCpuData.isSelected();
				try {
					nAnalyticsSettings.analyticsSettings.writeOption("analytics.noCPU", !chckbxAllowCpuData.isSelected());
				}catch (Exception ex) {}
				textPane.setText(ArrayUtils.StringArrayUtils.addFrom(demoData.fetch_data_dump(), 0));
			}
		});
		chckbxAllowCpuData.setSelected(nAnalyticsSettings.allowCPU);
		chckbxAllowCpuData.setToolTipText("Your Data: " + CPUUtil.parse().toString());
		
		JCheckBox chckbxAllowGpuData = new JCheckBox("Allow GPU Data");
		chckbxAllowGpuData.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				nAnalyticsSettings.allowGPU = chckbxAllowGpuData.isSelected();
				try {
					nAnalyticsSettings.analyticsSettings.writeOption("analytics.noGPU", !chckbxAllowGpuData.isSelected());
				}catch (Exception ex) {}
				textPane.setText(ArrayUtils.StringArrayUtils.addFrom(demoData.fetch_data_dump(), 0));
			}
		});
		chckbxAllowGpuData.setSelected(nAnalyticsSettings.allowGPU);
		chckbxAllowGpuData.setToolTipText("Your Data: " + GPUUtil.parse().toString());
		
		JLabel lblSampleOutput = new JLabel("Sample Output:");
		
		JScrollPane scrollPane_1 = new JScrollPane();
		
		JButton btnTriggererror = new JButton("Trigger 'Error'");
		btnTriggererror.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				demoData.registerError(new Exception(StringsUtil.randomString(32)));
				textPane.setText(ArrayUtils.StringArrayUtils.addFrom(demoData.fetch_data_dump(), 0));
			}
		});
		GroupLayout gl_panel_1 = new GroupLayout(panel_1);
		gl_panel_1.setHorizontalGroup(
			gl_panel_1.createParallelGroup(Alignment.TRAILING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addContainerGap()
					.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
						.addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE)
						.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 413, Short.MAX_VALUE)
						.addComponent(chckbxAllowNetworkData)
						.addComponent(chckbxAllowDetailedOs)
						.addComponent(lblHoverOverA)
						.addComponent(lblTheFloowingBoxes)
						.addComponent(chckbxAllowUid)
						.addComponent(lblRegisteredAnalytics)
						.addGroup(gl_panel_1.createSequentialGroup()
							.addGroup(gl_panel_1.createParallelGroup(Alignment.LEADING)
								.addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING)
									.addComponent(chckbxAllowGpuData)
									.addComponent(chckbxAllowCpuData))
								.addComponent(lblSampleOutput))
							.addPreferredGap(ComponentPlacement.RELATED, 169, Short.MAX_VALUE)
							.addComponent(btnTriggererror)))
					.addContainerGap())
		);
		gl_panel_1.setVerticalGroup(
			gl_panel_1.createParallelGroup(Alignment.LEADING)
				.addGroup(gl_panel_1.createSequentialGroup()
					.addGap(9)
					.addGroup(gl_panel_1.createParallelGroup(Alignment.TRAILING)
						.addGroup(gl_panel_1.createSequentialGroup()
							.addComponent(lblHoverOverA)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(lblTheFloowingBoxes)
							.addGap(8)
							.addComponent(chckbxAllowDetailedOs)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(chckbxAllowNetworkData)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(chckbxAllowUid)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(chckbxAllowCpuData)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(chckbxAllowGpuData)
							.addPreferredGap(ComponentPlacement.RELATED)
							.addComponent(lblSampleOutput))
						.addComponent(btnTriggererror))
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(scrollPane_1, GroupLayout.DEFAULT_SIZE, 95, Short.MAX_VALUE)
					.addPreferredGap(ComponentPlacement.RELATED)
					.addComponent(lblRegisteredAnalytics)
					.addGap(18)
					.addComponent(scrollPane, GroupLayout.PREFERRED_SIZE, 113, GroupLayout.PREFERRED_SIZE))
		);
		
		textPane = new JTextPane();
		textPane.setText(ArrayUtils.StringArrayUtils.addFrom(demoData.fetch_data_dump(), 0));
		textPane.setEditable(false);
		scrollPane_1.setViewportView(textPane);
		
		list = new JList();
		scrollPane.setViewportView(list);
		panel_1.setLayout(gl_panel_1);
	}
	
	public JList getRegisteredList() {
		return list;
	}
	
	public void updateList(final LinkedList<nAnalytics> registered) {
		final LinkedList<String> apply = new LinkedList<String>();
		for (final nAnalytics register : registered) {
			apply.add(register.toRList());
		}
		this.list.setListData(ArrayUtils.listToArray(apply));
	}
}
